package bookpos.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;

/**
 * @author 吴泽标
 *
 */
public class IHibernateDao {
  private static final Log log=LogFactory.getLog(IHibernateDao.class);
  
  protected String className;
  public IHibernateDao(){}
  public IHibernateDao(String className){this.className = className;}
  private static SessionFactory sessionFactory;
  @Resource(name="sessionFactory")
  public void setSessionFactory(SessionFactory sessionFactory) { 
   
      this.sessionFactory = sessionFactory;
  }
  public void sessionFlush(){
    try{
    this.sessionFactory.getCurrentSession().flush();
    }catch(Exception e){
      System.out.println("warming:"+e.getMessage());
    }
  }
  protected SessionFactory getSessionFactory() { 
    return this.sessionFactory;
  }
  protected Session getSession() { 
    sessionFlush();
    return this.sessionFactory.getCurrentSession();
  }
  public void _save(Object vo){
    getSession().save(vo);
  }
  public void _update(Object vo){
    getSession().update(vo);
  }
  public void _delete(Object vo){
    getSession().delete(vo);
  }
  public List _createQueryList(String hql){
    return getSession().createQuery(hql).list();
  }
  public static Query _createQuery(String hql){
    return sessionFactory.getCurrentSession().createQuery(hql);
  }
  public static List _findList(String hql) {
    return sessionFactory.getCurrentSession().createQuery(hql).list();
  }
  
  
  /**
   * 保存
   */
  public  boolean save(Object obj) {
    Session session = getSession();
    try {
        Transaction tx = session.beginTransaction(); // 开始事务
        
        session.save(obj);//保存操作
        
        tx.commit(); // 提交事务
        
        return true;
    } catch (RuntimeException e) {
        session.getTransaction().rollback(); // 回滚事务
        e.printStackTrace();
        return false;
    } 
  }
  /**
   * 更新
   */
  public boolean update(Object obj) {
    Session session = getSession();
    try {
        Transaction tx = session.beginTransaction(); // 开始事务
        
        session.update(obj);//更新操作
        
        tx.commit(); // 提交事务
        return true;
    } catch (RuntimeException e) {
        session.getTransaction().rollback(); // 回滚事务
        System.out.println("【Tag.update error:】\n"+e.getMessage());          
        return false;
    } 
  }
  /**
   * 删除
   */
  public boolean delete(Object obj){
    Session session = getSession();
    log.debug("delete :");
    try {
    
          Transaction tx = session.beginTransaction(); // 开始事务
          
          session.delete(obj);
          
          tx.commit(); // 提交事务
      
        log.debug("delete successful");
         return true;
    } catch (RuntimeException re) {
        log.error("delete failed", re);
        session.getTransaction().rollback(); // 回滚事务
        System.out.println("【AddPraise.delete error:】\n"+re.getMessage());          
        return false;
    }
  }
  public boolean delete(String coloum,Object value){
    Session session = getSession();
    log.debug("delete by id:");
    try {
    
          Transaction tx = session.beginTransaction(); // 开始事务
          Query query=session.createQuery("delete "+className+" where "+coloum+"="+value+"");
          query.executeUpdate();
          tx.commit(); // 提交事务
      
        log.debug("delete successful");
         return true;
    } catch (RuntimeException re) {
        log.error("delete failed", re);
        session.getTransaction().rollback(); // 回滚事务
        System.out.println("【delete error:】\n"+re.getMessage());          
        return false;
    } 
  }
  /**
   * 按id删除
   */
  public boolean deleteById(Integer id){
    Session session = getSession();
    log.debug("delete by id:");
    try {
    
          Transaction tx = session.beginTransaction(); // 开始事务
          
          Object obj=session.get(Class.forName(className), id);
          
          session.delete(obj);
          
          tx.commit(); // 提交事务
          session.flush(); 
        log.debug("delete successful");
         return true;
    } catch (RuntimeException re) {
        log.error("delete failed", re);
        session.getTransaction().rollback(); // 回滚事务
        System.out.println("【delete error:】\n"+re.getMessage());          
        return false;
    } catch (ClassNotFoundException e) { e.printStackTrace();return false;
    } 
  }
  /**
   * 按id查找
   */
  public Object findUpdateById(Integer id){
    try {
          Object obj=getSession().load(Class.forName(className), id);
          return obj;
    } catch (RuntimeException re) {
        System.out.println("【delete error:】\n"+re.getMessage());          
        return null;
    } catch (ClassNotFoundException e) { e.printStackTrace();return null;
    } 
  }
  public Object findById(Integer id){
    Session session = getSession();
    log.debug("delete by id:");
    try {
    
          Transaction tx = session.beginTransaction(); // 开始事务
          
          Object obj=session.get(Class.forName(className), id);
          
          tx.commit(); // 提交事务
      
        log.debug("delete successful");
         return obj;
    } catch (RuntimeException re) {
        log.error("delete failed", re);
        session.getTransaction().rollback(); // 回滚事务
        System.out.println("【delete error:】\n"+re.getMessage());          
        return null;
    } catch (ClassNotFoundException e) { e.printStackTrace();return false;
    } 
  }
  /**
   * 查询
   */
  public List findAll() {
    Session session = getSession();
    Transaction tx = null;
    List list=null;
    try {
      tx = session.beginTransaction(); // 开始事务
      Criteria criteria = session.createCriteria(Class.forName(className));
      list = criteria.list();
        tx.commit();
        return list;
        
    } catch (RuntimeException e) {
        tx.rollback();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } 
    return list;
  }
  
//  /**
//   * 部分查询，返回查询条数，可用于分页浏览
//   */
//  public Page findAll(int pageNum, int pageSize) {
//    Session session = getSession();
//    Transaction tx = null;
//    try {
//        tx = session.beginTransaction();
//
//        int firstResult =(pageNum-1)*pageSize;
//        List list = session.createQuery(//
//                "FROM "+className+"")//
//                .setFirstResult(firstResult)//
//                .setMaxResults(pageSize)//
//                .list();
//        // 查询总记录数
//        Long count = (Long) session.createQuery(//
//                "SELECT COUNT(*) FROM "+className)//
//                .uniqueResult();
//        tx.commit();
//        return new Page(count.intValue(), list, pageNum, pageSize);
//        //  返回结果
//    } catch (RuntimeException e) {
//        tx.rollback();
//        return null;
//    } 
// }
  /**
   * 部分查询，按列值查询
   */
  public List find(String propertyName, Object value)  {
    log.debug("finding "+className+" by Property");
    Session session = getSession();
    Transaction tx = null;
    List list=null;
    try {
        tx = session.beginTransaction(); // 开始事务
        
        Criteria criteria = session.createCriteria(Class.forName(className)); 
        criteria.add(Expression.eq(propertyName,value)); 
        list = criteria.list(); // 要先获取到这个对象
        
        tx.commit();
        log.debug("find by example successful, result size: "
            + list.size());
        return list;
    } catch (RuntimeException re) {
        log.error("find by example failed", re);
        return new ArrayList();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      return new ArrayList();
    }
  }
  /**
   * 部分查询，按列值查询
   */
  public List find(String column1, Object value1,String column2, Object value2)  {
    log.debug("finding "+className+" by Property");
    Session session = getSession();
    Transaction tx = null;
    List list=null;
    try {
        tx = session.beginTransaction(); // 开始事务
        
        Criteria criteria = session.createCriteria(Class.forName(className)); 
        criteria.add(Expression.eq(column1,value1)); 
        criteria.add(Expression.eq(column2,value2)); 
        list = criteria.list(); // 要先获取到这个对象
        
        tx.commit();
        log.debug("find by example successful, result size: "
            + list.size());
        return list;
    } catch (RuntimeException re) {
        log.error("find by example failed", re);
        return new ArrayList();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      return new ArrayList();
    }
  }
  public List findByKey(String column,String key) {
    
    Session session = getSession();
    Transaction tx = null;
    List list=null;
    try {
        tx = session.beginTransaction(); // 开始事务
        
            
            Criteria criteria = session.createCriteria(Class.forName(className)); 
            criteria.add(Expression.like(column,"%"+key+"%")); 
          
            list=criteria.list();
            
            tx.commit(); // 提交事务
        log.debug("find by example successful, result size: "
            + list.size());
        return list;
        
    } catch (RuntimeException re) {
        log.error("find by example failed", re);
        return new ArrayList();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      return new ArrayList();
    }
  }

  
  
  
  public List findByHql(String hql) {
    log.debug("***************根据sql查找："+hql+"********************");
    Session session = getSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();

        List list = session.createQuery(hql).list();

        tx.commit();
      
    log.debug("***************根据sql查找返回记录数："+list.size()+"********************");  
        
        return list;
        //  返回结果
    } catch (RuntimeException e) {
        tx.rollback();
        e.printStackTrace();
       return null;
    }
  }
  
  public List findListByHql(String hql,int size) {
    log.debug("***************根据sql查找："+hql+"********************");
    Session session = getSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();

        List list = session.createQuery(hql).setFirstResult(0).setMaxResults(size).list();

        tx.commit();
      
        return list;
        //  返回结果
    } catch (RuntimeException e) {
        tx.rollback();
       return null;
    }
  }
  
//  /**
//   * 部分查询，返回查询条数，可用于分页浏览
//   */
//  public Page findByHql(String hql,int pageNum, int pageSize) {
//    Session session = getSession();
//    Transaction tx = null;
//    try {
//        tx = session.beginTransaction();
//        System.out.println("hql:"+hql+" \npageNum:"+pageNum+"\npageSize:"+pageSize);
//        int firstResult =(pageNum-1)*pageSize;
//        List list = session.createQuery(hql)//
//                .setFirstResult(firstResult)//
//                .setMaxResults(pageSize)//
//                .list();
//        // 查询总记录数
//        Long count = (Long) session.createQuery(//
//                "SELECT COUNT(*)"+hql)//
//                .uniqueResult();
//        tx.commit();
//        return new Page(count.intValue(), list, pageNum, pageSize);
//        //  返回结果
//    } catch (RuntimeException e) {
//        tx.rollback();
//        e.printStackTrace();
//        return null;
//    } 
// }
  
  public List findByHql(String hql, Integer value)  {
    log.debug("finding "+className+" by Property");
    Session session = getSession();
    Transaction tx = null;
    List list=null;
    try {
        tx = session.beginTransaction(); // 开始事务
        
        Query query = session.createQuery(hql);
        query.setInteger(0, value);
        //query.executeUpdate();
        list = query.list(); // 要先获取到这个对象
        tx.commit();
        log.debug("find by example successful, result size: "
            + list.size());
        return list;
    } catch (RuntimeException re) {
        log.error("find by example failed", re);
        return new ArrayList();
    }
  }
  
  public List findBySql(String sql) {
    log.debug("***************根据sql查找："+sql+"********************");
    Session session = getSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();

        List list = session.createSQLQuery(sql).list();

        tx.commit();
      
    log.debug("***************根据sql查找返回记录数："+list.size()+"********************");  
        
        return list;
        //  返回结果
    } catch (RuntimeException e) {
        tx.rollback();
       return new ArrayList();
    } 
  }

public int saveOrUpdateByHql(String hql) {
    
    try {
      //hql = "update User set password='"+password+"' where id="+id+""
      return _createQuery(hql).executeUpdate();
    } catch (RuntimeException e) {
      e.printStackTrace();
      return -1;
    } 
  }

}
